package world.criver.mm_vworld_server.function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import world.criver.crc.CRC;
import world.criver.mm_vworld_server.config.conConfig;

import java.io.*;

@Component
public class funFile {
    @Autowired
    private conConfig conConfig;

    private CRC crc=new CRC();

    /**
     * 读取MM文件
     * @param f
     * @return
     */
    public String readFileOfMM(File f){
        if(!f.getName().endsWith(".mm"))return null;
        try(BufferedReader re=new BufferedReader(new FileReader(f))){
            String qw="",as;
            while((as=re.readLine())!=null)qw+=crc.decrypt(conConfig.getEncryptKey(), as)+"\n";
            return qw;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 写入MM文件
     * @param data
     * @param f
     * @return
     */
    public boolean writeFileOfMM(String data,File f){
        try {
            if(!f.getName().endsWith(".mm"))return false;
            if(!f.getParentFile().exists())f.getParentFile().mkdirs();
            if(!f.exists()) f.createNewFile();
            try(BufferedWriter wr=new BufferedWriter(new FileWriter(f))) {
                String[] da = data.split("\n");
                for (String s : da) wr.write(crc.encrypt(conConfig.getEncryptKey(), s) + "\n");
            }catch (Exception ee){
                ee.printStackTrace();
                return false;
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
